// 这里是外置路由模块
const express = require('express');
// 引入path模块进行拼串
const path = require('path');
// 引入工具模块
const tools = require('./tools');

// 创建路由对象
const router = express.Router();


// 监听以get方式请求index页面
router.get('/index.html', (req, res) => {
    console.log(req.url);

    tools.readData((data) => {
        data.list.sort((a, b) => b.id - a.id);
        res.render('index.html', data);
    });
});

// 监听以get方式请求details页面
router.get('/details', (req, res) => {

    console.log(req.query);

    tools.readData((data) => {
        let info = data.list.find((v, i) => {
            return v.id == req.query.id;
        });

        console.log(info);
        res.render('details.html', info);
    });
});

// 监听以get方式请求submit页面
router.get('/submit', (req, res) => {
    res.sendFile(path.join(__dirname, 'pages', 'submit.html'));
});
// 监听submit页面的get请求
router.get('/add', (req, res) => {
    console.log('submit进行了get请求');

    console.log(req.query);

    tools.writeData(req.query, () => {
        res.redirect('/index.html');
    });
});
// 监听submit页面的post请求
router.post('/add', (req, res) => {
    console.log('submit进行了post请求');

    console.log(req.body);

    tools.writeData(req.body, () => {
        res.redirect('/index.html');
    });
});
// 监听静态资源得请求
// router.use('/assets', (req, res) => {
//     console.log(req.url);
//     res.sendfile(path.join(__dirname, 'assets', req.url));
// });
// 静态资源托管
// router.use('/assets', express.static('assets'));

router.use('/aa', (req, res) => { //use会去掉/aa..
    console.log(req.url);
    res.send('???');
});

module.exports = router;